/**
 * File:   PutAction.java
 * Author: Gvennet
 */
package gui.actions;

import dht.identifier.identifier.Identifier;
import dht.identifier.identifier.Identifiers;
import dht.network.Network;
import dht.node.DHTNodeModel;
import dht.node.DHTNodeRow;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.List;

/**
 * todo write javadoc
 */
public final class PutAction extends AbstractAction
{

	private final DHTNodeModel nodeModel;

	private final JTextField putText;

	private final Network network;

	public PutAction(DHTNodeModel nodeModel, JTextField putText, Network network)
	{
		super("Ввести");
		this.nodeModel = nodeModel;
		this.putText = putText;
		this.network = network;
		putValue(SHORT_DESCRIPTION, "Ввести данные");
		putValue(MNEMONIC_KEY, KeyEvent.VK_P);
	}

	public void actionPerformed(ActionEvent e)
	{
		final String text = putText.getText();
		if (text != null && !text.isEmpty())
		{
			String[] parts = text.replaceAll("[.,-:;!?]\"", " ").split(" ");
			for (final String part : parts)
			{
				if (part.length() > 3)
				{
					Identifier partId = Identifiers.createIdentifier(part, 20);
					List<DHTNodeRow> nearestNodes = nodeModel.get(partId);
					for (int i = 0; i < 3; i++)
					{
						if (nearestNodes.size() > i)
						{
							try
							{
								network.sendPutValueRequest(nearestNodes.get(i).getInetAddress(), nearestNodes.get(i).getPort(), Identifiers.createIdentifier(part, 20), text);
							}
							catch (IOException e1)
							{
								//do nothing
							}
						}
					}
				}
			}

			putText.setText("");
		}
	}
}
